package com.freesky.quartz.task;

import cn.hutool.core.date.DateUtil;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayUserDtbankcustActivityconfigQueryRequest;
import com.alipay.api.response.AlipayUserDtbankcustActivityconfigQueryResponse;
import com.freesky.biz.activity.domain.TAlipayActivityConfig;
import com.freesky.biz.activity.mapper.AlipayActivityConfigMapper;
import com.freesky.biz.pay.config.AliPayConfiguration;
import com.freesky.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;

@Slf4j
@Component("alipayActivityMonitor")
public class AlipayActivityMonitor {

    private static final Logger logger = LoggerFactory.getLogger(AlipayActivityMonitor.class);

    @Autowired
    private AliPayConfiguration aliPayConfiguration;

    @Autowired
    private AlipayActivityConfigMapper alipayActivityConfigMapper;

    /**
     *     立减: DISCOUNT
     *     通用渠道红包: VOUCHER
     *     首绑有礼: FIRST_BIND_CARD_GIFT
     */
    public void taskProcess() {
        List<TAlipayActivityConfig> activityConfigList = alipayActivityConfigMapper.selectActivityConfigList();
        for(TAlipayActivityConfig alipayActivityConfig : activityConfigList){
            String activityType = alipayActivityConfig.getActivityType().trim();
            if("立减".equalsIgnoreCase(activityType)){
                activityType = "DISCOUNT";
            } else if("渠道通用红包".equalsIgnoreCase(activityType)){
                activityType = "VOUCHER";
            } else if("首绑有礼".equalsIgnoreCase(activityType)){
                activityType ="FIRST_BIND_CARD_GIFT";
            }
            //UPDATE tec_alipay_activity_config SET id = REPLACE(id, UNHEX('E2808B'), '');
            //insert into tec_alipay_activity_config(id,activity_name,activity_type,create_date) select DISTINCT REPLACE(stock_id, UNHEX('E2808B'), ''),stock_name,stock_type,now() from tec_alipay_bill
            //ACT790DSC01173577​
            AjaxResult result = queryActivityConfig(alipayActivityConfig.getId(),activityType);
            if(result.isSuccess()){
                TAlipayActivityConfig resultActivityConfig =   (TAlipayActivityConfig)result.get("data");
                alipayActivityConfigMapper.updateActivityConfig(resultActivityConfig);
            }
        }
    }

    public AjaxResult queryActivityConfig(String activityId, String activityType) {
        try {
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            certAlipayRequest.setServerUrl(aliPayConfiguration.getGatewayUrl());
            certAlipayRequest.setAppId(aliPayConfiguration.getAppId());
            certAlipayRequest.setPrivateKey(aliPayConfiguration.getPrivateKey());
            certAlipayRequest.setFormat("json");
            certAlipayRequest.setCharset(aliPayConfiguration.getCharset());
            certAlipayRequest.setSignType(aliPayConfiguration.getSignType());
            certAlipayRequest.setCertPath(aliPayConfiguration.getAppCertPath());
            certAlipayRequest.setAlipayPublicCertPath(aliPayConfiguration.getAlipayCertPath());
            certAlipayRequest.setRootCertPath(aliPayConfiguration.getAlipayRootCertPath());
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

            AlipayUserDtbankcustActivityconfigQueryRequest request = new AlipayUserDtbankcustActivityconfigQueryRequest();
            request.setBizContent("{" +
                    "  \"activity_id\":\""+activityId+"\"," +
                    "  \"activity_type\":\""+activityType+"\"" +
                    "}");

            log.info(request.getBizContent());
            AlipayUserDtbankcustActivityconfigQueryResponse response = alipayClient.certificateExecute(request);
            log.info(response.getBody());
            if(response.isSuccess()){
                TAlipayActivityConfig alipayActivityConfig = new TAlipayActivityConfig();
                alipayActivityConfig.setId(response.getActivityId());
                alipayActivityConfig.setActivityStatus(response.getActivityStatus());
                alipayActivityConfig.setActivityName(response.getActivityName());
                alipayActivityConfig.setCountLimit(response.getCountLimit());
                alipayActivityConfig.setUseScene(response.getUseScene());
                alipayActivityConfig.setBeginTime(DateUtil.format(response.getActivityTimeInfo().getBeginTime(),"yyyy-MM-dd HH:mm:ss"));
                alipayActivityConfig.setEndTime(DateUtil.format(response.getActivityTimeInfo().getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                alipayActivityConfig.setTotalBudget(response.getBudgetInfo().getBudgetConfigInfo().getTotalBudget());
                alipayActivityConfig.setUsedCount(response.getBudgetInfo().getBudgetRealTimeInfo().getUsedCount());
                alipayActivityConfig.setUsedAmount(response.getBudgetInfo().getBudgetRealTimeInfo().getUsedAmount());
                alipayActivityConfig.setRemainingBudget(response.getBudgetInfo().getBudgetRealTimeInfo().getRemainingBudget());
                alipayActivityConfig.setRefundAmount(response.getBudgetInfo().getBudgetRealTimeInfo().getRefundAmount());
                alipayActivityConfig.setSendCount(response.getBudgetInfo().getBudgetRealTimeInfo().getSendCount());
                alipayActivityConfig.setSendAmount(response.getBudgetInfo().getBudgetRealTimeInfo().getSendAmount());
                return AjaxResult.success(response.getMsg(),alipayActivityConfig);
            } else {
                return AjaxResult.error(response.getSubMsg());
            }
        } catch (Exception ioe){
            ioe.printStackTrace();
            logger.error(ioe.getMessage());
            return AjaxResult.error("操作系统，系统异常");
        }

    }


}
